define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        config = require("./setting"),
        method = require("./method");
    $(document).on('click', '[data-toggle="trigger"]', function(e) {
        e && e.preventDefault();
        var tg = $(this).data('target').split(':')
        tg && $(tg[0]).trigger(tg[1]);

    })
    $(document).on('click', '[data-toggle="alert"]', function(e) {
        e && e.preventDefault();
        var $this = $(this),
            msg = $this.data("msg") || "确定",
            url = $this.data("url") || "";
        msgbox.alert(msg, function() {
            if (url) {
                document.location = url;
            }

        });

    })
    var $loadAlert = $('[data-toggle="loadAlert"]');
    $loadAlert.length > 0 && (function() {
        var msg = $loadAlert.data("msg") || "确定",
            url = $loadAlert.data("url") || "";
        setTimeout(function() {
            msgbox.alert(msg, function() {
                if (url) {
                    document.location = url;
                }

            });
        }, 200)

    })();
    $(document).on('click', '[data-toggle="back"]', function(e) {
            e && e.preventDefault();
            var u = $(this).data("url");
            u ? window.location = u : window.history.go(-1)
        })
        // $("[data-toggle=popover]").popover();
        // $(document).on('click', '.popover-title .close', function(e) {
        //     var $target = $(e.target),
        //         $popover = $target.closest('.popover').prev();
        //     $popover && $popover.popover('hide');
        // });
    $.fn.extend({
        popoverClosable: function(options) {
            var defaults = {
                template: '<div class="popover">\
<div class="arrow"></div>\
<div class="popover-header">\
<button type="button" class="close m-r-xs m-t-xs" data-dismiss="popover" aria-hidden="true">&times;</button>\
<h3 class="popover-title"></h3>\
</div>\
<div class="popover-content"></div>\
</div>'
            };
            options = $.extend({}, defaults, options);
            var $popover_togglers = this;
            $popover_togglers.popover(options);
            $popover_togglers.on('click', function(e) {
                e.preventDefault();
                $popover_togglers.not(this).popover('hide');
            });
            $.each($popover_togglers, function(index, val) {
                var $this = $(this),
                    hover = $this.data("hover");

                if (hover) {
                    $this.on({
                        mouseenter: function(e) {
                            $popover_togglers.not(this).popover('hide');
                            $this.popover('show');
                        }
                    });
                    // $(document).on('click', function(e) { 
                    //   if ($(e.target).closest(".popover").length) {
                    //         return false;
                    //   }

                    //  $this.popover('hide');
                    // })
                };
            });


            $(document).on('click', '[data-dismiss="popover"]', function(e) {
                $popover_togglers.popover('hide');
            });
        }
    });
    $('[data-toggle="popover"]').popoverClosable();
    $(document).on('click', '[data-toggle^="class"]', function(e) {

        if (e.target.type != "checkbox" && e.target.type != "radio") {
            e && e.preventDefault();
        };
        var $this = $(e.target),
            $class, $target, $tmp, $classes, $targets;
        !$this.data('toggle') && ($this = $this.closest('[data-toggle^="class"]'));
        $class = $this.data()['toggle'];
        $target = $this.data('target') || $this.attr('href');
        $class && ($tmp = $class.split(':')[1]) && ($classes = $tmp.split(','));
        $target && ($targets = $target.split(','));
        $targets && $targets.length && $.each($targets, function(index, value) {
            ($targets[index] != '#') && $($targets[index]).toggleClass($classes[index]);
        });
        $this.toggleClass('active');


        var $$this = $(this);
        var ajax = $$this.data("ajax"),
            fun = $$this.data("fun"),
            $remote = $$this.data('remote') || $$this.attr('href');
        var rfun = null;
        if (fun) {
            switch (fun) {
                case "shelves":
                    rfun = function(d) {
                        if (config.issucceed(d)) {
                            config.msg.suc(d.message || config.lang.shelvesSuccess, d.url)
                        } else {
                            config.msg.error(d.message || config.lang.shelvesError, d.url)
                        }
                    }
            }
        };
        ajax && method.post($remote, rfun, null, null, {
            toggle: $$this.hasClass('active')
        });
    })
    $(document).on('click', '[data-toggle="ajaxModal"]',
        function(e) {

            var $this = $(this),
                $confirm = $this.data('confirm'),
                $confirm = (typeof $confirm == "undefined" ? false : $confirm);
            var done = function() {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $remote = $this.data('remote') || $this.attr('href'),
                    $data = $this.data("set"),
                    $modal = $('<div class="modal fade" id="ajaxModal"><div class="modal-body "></div></div>');

                $(document).append($modal);
                $modal.modal();
                $.ajax($remote, {
                    type: "get",
                    dataType: "html",
                    data: $data
                }).done(function(result) {
                    $modal.append2(result, function() {
                        var $form = $('form.form-validate', $modal);
                        $form.length > 0 && require.async("dist/form/init", function(form) {
                            if ($("button[type='submit']", $modal).length) {
                                $("button[type='submit']", $modal).removeAttr('disabled');
                            }
                            form.init($form);
                            $('[data-toggle="popover"]').popover();
                            var $select2 = $('[data-toggle="select2_4"]',$form);
                            $select2.length > 0 && require.async(['select2_4'], function() {
                                $select2.each(function() {
                                    var t = $(this),
                                        n = {},
                                        c = t.data('maxcount'),
                                        o = t.data('chang'),
                                        r = t.data('remote') || t.attr('href'),
                                        pid=t.data("pid"),
                                        required_msg = t.data("msgRequired") || t.data("placeholder");
                                    c && (n.maximumSelectionSize = c);
                                    if (o) {
                                        switch (o) {
                                            case "submit":
                                                {
                                                    t.on("change", function(e) {
                                                        t.closest("form ").submit();
                                                    })
                                                }
                                        }
                                    };
                                    if (r) {
                                        if(pid!=undefined){
                                            r=r.format(pid);
                                        }
                                        t.select2({
                                            ajax: {
                                                url: r,
                                                dataType: 'json',
                                                delay:500,
                                                data: function(params) {
                                                    return {
                                                        q: params.term, // search term
                                                        page: params.page || 1
                                                    };
                                                },
                                                processResults: function(data, params) {
                                                    if (config.issucceed(data)) {
                                                        params.page = params.page || 1;
                                                        if(params.page==1){
                                                            data.items.unshift({
                                                                "id": "js_select2_4placeholder",
                                                                "value": t.data("placeholder")
                                                            });
                                                        }
                                                       
                                                        return {
                                                            results: data.items,
                                                            pagination: {
                                                                more: (params.page * data.page_num) < data.total_count
                                                            }
                                                        };
                                                    }else {
                                                        config.msg.error(data.message || config.lang.sendError);
                                                    }
                                                },
                                                cache: true
                                            },
                                            escapeMarkup: function(markup) {
                                                return markup;
                                            }, 
                                            minimumInputLength: 0,
                                            templateResult: formatRepo,
                                            templateSelection: formatRepoSelection 
                                        });
                                    } else {
                                        t.select2(n)
                                    }
                                    t.change(function(){
                                        var $this=$(this);
                                        if($this.val()=="js_select2_4placeholder"){
                                            $this.find("option:selected").attr("value","");
                                        }
                                    });

                                })
                            });
                        });
                        $this.trigger('init', $modal)
                    });
                })
            }

            $confirm && config.msg.msgbox.confirm({
                message: $this.data('confirmMsg') || "确认",
                buttons: {
                    confirm: {
                        label: $this.data('confirmText') || "确定"
                    }
                },
                callback: function(result) {
                    if (result) {
                        done();
                    }
                }
            });
            !$confirm && done();

        })
    $(document).on('click.dropdown-menu', '.dropdown-select > .js_custom_list', function(e) {
        e.preventDefault();
        return false;
    })
    function formatRepo (repo) {
    if (repo.loading) return repo.text;

    var markup = '<li>' +repo.value + 
    '</li>';

    return markup;
  }

  function formatRepoSelection (repo) {
    return repo.value || repo.text;
  }
    $(document).on('click.dropdown-menu', '.dropdown-select > li > a', function(e) {
        e.preventDefault();
        var $item = $(e.target),
            $select, $checked = false,
            $menu, $label, $labelHolder, $items, $text;

        !$item.is('a') && ($item = $item.closest('a'));

        $menu = $item.closest('.dropdown-menu');
        $label = $menu.parent().find('.dropdown-label');
        $labelHolder = $label.text();
        $select = $item.find('input');
        $checked = $select.is(':checked');
        if ($select.is(':disabled')) return;
        if ($select.attr('type') == 'radio' && $checked) return;
        if ($select.attr('type') == 'radio') $menu.find('li').removeClass('active');
        $item.parent().removeClass('active');
        !$checked && $item.parent().addClass('active');
        $select.prop("checked", !$select.prop("checked"));

        $items = $menu.find('li > a > input:checked');
        if ($items.length) {
            $text = [];
            $items.each(function() {
                var $str = $(this).parent().text();
                $str && $text.push($.trim($str));
            });

            $text = $text.length < 6 ? $text.join(', ') : ' 选中' + $text.length + '项';
            $label.html($text);
        } else {
            $label.html($label.data('placeholder'));
        }
        $select.trigger('change', [$select.val()]);
        var even = $menu.data("change")
        if (even) {
            switch (even) {
                case "submit":
                    {
                        $menu.closest("form ").submit();
                    }
            }
        };

    });
    $(document).on("click", 'table [data-toggle="removeRow"]', function() {
        var $tr = $(this).closest("tr");
        $tr.fadeOut(function() {
            $tr.remove();
        })
    })


    $(document).on('click', '[data-toggle="ajaxPost"]', function(e) {
        e.preventDefault();
        var $this = $(this),
            $remote = $this.data('remote') || $this.attr('href'),
            $confirm = $this.data('confirm'),
            $msgType = $this.data('msgType'),
            $data = $this.data("set"),
            $remove = $this.data('remove');
        $confirm = (typeof $confirm == "undefined" ? true : $confirm);
        $this.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>')
        var done = function() {
            var org = $this.html();
            $this.button('loading');
            $.post($remote, $data).done(function(d) {
                $this.button('reset');
                if (config.issucceed(d)) {
                    if ($remove) {
                        var $el = $this.closest($remove);
                        $el.fadeOut(function() {
                            $el.remove();
                        });
                    };
                    config.msg.suc(d.message || config.lang.removeSuccess, d.url);
                    d.callback && eval(d.callback);
                } else {
                    config.msg.error(d.message || config.lang.removeError, d.url)
                }
            }).fail(function() {
                $this.button('reset');
                config.msg.info(config.lang.exception)
            });

        }
        var retrunMsg = function(type) {
            switch (type) {
                case "refund":
                    {
                        return config.lang.confirmRefund;
                    }
                case "refundGoods":
                    {
                        return config.lang.confirmRefundGoods;
                    }
            }
        }
        var confirmMsg = $msgType ? retrunMsg($msgType) : $this.data('msg');
        $confirm && config.msg.msgbox.confirm({
            message: confirmMsg || config.lang.confirmPost,
            buttons: {
                confirm: {
                    label: $this.data('confirmText') || "确定"
                }
            },
            callback: function(result) {
                if (result) {
                    done();
                }
            }
        });
        !$confirm && done();
    });
    $(document).on('click', ".js_remove_dd_item", function() {
        var $this = $(this),
            $li = $this.closest('.dd-item');

        $li.fadeOut(function() {
            $li.remove();
            if ($('.dd-item').length == 0) {
                $("#noitems").removeClass('hide')
            };
        })

    })
    $(document).on('click', '[data-toggle^="refresh"]', function(e) {
        e && e.preventDefault();
        window.location.reload()
    })
    $(document).on('click', 'ol li [data-toggle="ajaxRemove"]',
        function(e) {
            e.preventDefault();
            var $this = $(this),
                $remote = $this.data('remote') || $this.attr('href'),
                $confirm = $this.data('confirm');
            $confirm = (typeof $confirm == "undefined" ? true : $confirm);
            var done = function() {
                var org = $this.html();
                $this.html('<i class="fa fa-spinner fa-spin"></i>');
                $.post($remote).done(function(d) {
                    if (config.issucceed(d)) {
                        config.msg.suc(d.message || config.lang.removeSuccess, d.url)
                        var $li = $this.parents('li').first();
                        $li.find(".dd-handle").css({
                            'background-color': '#dff0d8'
                        })
                        $li.fadeOut(function() {
                            $li.remove();
                            if ($('.dd-item').length == 0) {
                                $noClassify.removeClass('hide')
                            };
                        })
                    } else {
                        $this.html(org);
                        config.msg.error(d.message || config.lang.removeError, d.url)
                    }
                }).fail(function() {
                    $this.html(org);
                    config.msg.info(config.lang.exception, d.url)
                });

            }
            $confirm && config.msg.msgbox.confirm($this.data('msg') || config.lang.confirmRemove, function(result) {
                if (result) {
                    done();
                }
            });
            !$confirm && done();
        });
    
    $(document).on('click', '[data-toggle="ajaxPostPage"]', function(e) {
        e.preventDefault();
        var $this = $(this),
            $remote = $this.data('remote') || $this.attr('href'),
            $confirm = $this.data('confirm'),
            $msgType = $this.data('msgType'),
            $data = $this.data("set"),
            $remove = $this.data('remove');
        $this.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>')
        var done = function() {
            var org = $this.html();
            $this.button('loading');
            $.post($remote,$data).done(function(d) {
                $this.button('reset');
                if (config.issucceed(d)) {
                    if ($remove) {
                        var $el = $this.closest($remove);
                        $el.fadeOut(function() {
                            $el.remove();
                        });
                    };
                    var $msg = d.message || config.lang.removeSuccess;
                    if(typeof d.message != "string"){
                        window.mainFrame ? document.getElementById("mainFrame").src = d.url : window.location = d.url;
                    }else{
                        config.msg.suc($msg , d.url);
                    }
                    
                    d.callback&&eval(d.callback);
                } else {
                    config.msg.error(d.message || config.lang.removeError, d.url)
                }
            }).fail(function() {
                $this.button('reset');
                config.msg.info(config.lang.exception)
            });

        }
        done();
    });

});